//
//  WelcomeView.swift
//  SinaWeibo
//
//  Created by celeste on 16/5/18.
//  Copyright © 2016年 celeste. All rights reserved.
//

import UIKit

class WelcomeView: UIView {

    override init(frame: CGRect) {
        
        super.init(frame: UIScreen.mainScreen().bounds)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        removeFromSuperview()
    }
    // 添加到窗口 - 已经显示
    override func didMoveToWindow() {
        super.didMoveToWindow()
        
        
        // 更新约束
        avatarImageView.snp_updateConstraints { (make) -> Void in
            make.centerY.equalTo(self).offset(-100)
        }
        
        // 动画
        // Damping: 弹力 0 ~ 1，越小越弹
        // Velocity: 速度，10 符合重力规则
        UIView.animateWithDuration(
            1.2,
            delay: 0.0,
            usingSpringWithDamping: 0.8,
            initialSpringVelocity: 10,
            options: [],
            animations: { () -> Void in
                
                self.layoutIfNeeded()
            }) { (_) -> Void in
                self.removeFromSuperview()
        }
    }

    // MARK: - 私有控件

    /// 头像视图
    private lazy var avatarImageView = UIImageView(ld_imageName: "avatar_default_big")
    /// 欢迎标签
    private lazy var welcomeLabel = UILabel(ld_text: "欢迎归来", fontSize: 18)

}

// MARK : - 设置界面
extension WelcomeView {
    
    private func setupUI() {
        
        // 1. 背景颜色
        backgroundColor = UIColor(patternImage: UIImage(named: "ad_background")!)
        
        // 2. 添加控件
        addSubview(avatarImageView)
        addSubview(welcomeLabel)
        
        // 3. 自动布局
        avatarImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(50)
        }
        welcomeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(avatarImageView)
            make.top.equalTo(avatarImageView.snp_bottom).offset(20)
        }
        // 4. 强行更新约束
        layoutIfNeeded()
        
        // 5. 设置头像
        avatarImageView.ld_setImageWithURL(UserAccount.sharedUserAccount.avatar_large,
            placeholderName: "avatar_default_big")
    }
}
